package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品，同时保存对应的口味数据
     * @param dishDTO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        // 保存菜品
        this.save(dishDTO);

        // 保存菜品口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(flavor -> {
            flavor.setDishId(dishDTO.getId());
        });
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public Page<DishDTO> pageCustom(Page<DishDTO> pageInfo, QueryWrapper<Dish> queryWrapper) {
        return baseMapper.selectPageCustom(pageInfo, queryWrapper);
    }

    @Override
    public DishDTO getByIdWithFlavor(Long id) {
        DishDTO dishDTO = new DishDTO();

        // 菜品
        Dish dish = this.getById(id);
        BeanUtils.copyProperties(dish, dishDTO);


        // 菜品口味
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper();
        wrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(wrapper);
        dishDTO.setFlavors(dishFlavorList);

        return dishDTO;
    }

    @Transactional
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        this.updateById(dishDTO);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DishFlavor::getDishId, dishDTO.getId());
        dishFlavorService.remove(wrapper);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(flavor -> {
            flavor.setDishId(dishDTO.getId());
        });
        dishFlavorService.saveBatch(flavors);
    }
}
